import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QSplitter, QTabWidget, QMessageBox, QDesktopWidget, QPushButton)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QPixmap
import pywinstyles
import base64
import icon_data

from settings_page import create_settings_page
from process_page import create_process_page
from merge_page import create_merge_page
from log_panel import create_log_panel
from video_crop_page import create_crop_page

from ui_utils import set_transparent_background, apply_content_styles

from hardware_check import HardwareCheckThread

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("裸眼3D视频转换器")
        self.setMinimumSize(1000, 600)
        
        # 设置图标
        self.setWindowIcon(self.create_icon_from_data())
        
        # 设置窗口样式
        pywinstyles.apply_style(self, "acrylic")
        pywinstyles.change_border_color(self, color="#CCFFFF")
        
        # 设置窗口背景透明 - 添加这一行
        self.setAttribute(Qt.WA_TranslucentBackground)
        
        # 设置窗口在屏幕中心
        self.center_window()
        
        # 初始化变量
        self.init_variables()
        
        # 初始化线程
        self.init_threads()
        
        # 创建UI
        self.init_ui()
        
        # 启动硬件检测线程
        self.hardware_thread.start()
        
        # 应用透明背景效果
        set_transparent_background(self)
    
    def init_variables(self):
        """初始化变量"""
        self.ffmpeg_path = ""
        self.ffmpeg_accel = "cpu"
        self.midas_accel = "cpu"
        self.stereo_accel = "cpu"
        self.input_video = ""
        self.fps = 0
        self.model = ""
        self.left_eye_video = ""
        self.right_eye_video = ""
        self.black_line = False
        self.black_line_width = 20
        self.min_strength = 0.02
        self.max_strength = 0.05
    
    def init_threads(self):
        """初始化线程"""
        self.hardware_thread = HardwareCheckThread()
        self.hardware_thread.hardware_detected.connect(self.update_hardware_options)
        self.hardware_thread.log_message.connect(self.append_log)
        self.ffmpeg_thread = None
        self.depth_thread = None
        self.stereo_thread = None
        self.cleanup_thread = None
    
    def init_ui(self):
        """初始化UI"""
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QHBoxLayout(central_widget)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)
        
        # 创建左侧功能菜单
        left_panel = self.create_left_panel()
        left_panel.setMaximumWidth(150)
        
        # 创建中间内容区域
        self.content_stack = QTabWidget()
        self.content_stack.setTabPosition(QTabWidget.West)
        self.content_stack.tabBar().setVisible(False)
        
        # 创建右侧日志区域
        right_panel = create_log_panel(self)
        right_panel.setMinimumWidth(400)
        
        # 应用右侧日志面板样式
        from style import style_log_panel
        style_log_panel(right_panel)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(left_panel)
        splitter.addWidget(self.content_stack)
        splitter.addWidget(right_panel)
        splitter.setSizes([150, 450, 400])
        
        main_layout.addWidget(splitter)
        
        # 创建四个页面
        create_settings_page(self)
        create_process_page(self)
        create_merge_page(self)
        create_crop_page(self)
        
        # 应用内容区域样式 - 取消注释
        self.apply_content_styles()
        
        # 默认显示设置页面
        self.switch_page(0)
        
        # 默认显示设置页面
        self.switch_page(0)
        
        # 初始禁用视频处理和左右眼合并按钮
        self.process_btn.setEnabled(False)
        self.merge_btn.setEnabled(False)
        self.crop_btn.setEnabled(False)  # 初始禁用裁切按钮
    
    def create_left_panel(self):
        """创建左侧面板"""
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        
        # 应用左侧面板样式
        from style import style_left_panel
        style_left_panel(left_panel)
        
        # 创建功能按钮
        self.settings_btn = QPushButton("初始设置")
        self.process_btn = QPushButton("视频处理")
        self.merge_btn = QPushButton("左右眼合并")
        self.crop_btn = QPushButton("视频裁切")  # 添加视频裁切按钮
        
        self.settings_btn.setCheckable(True)
        self.process_btn.setCheckable(True)
        self.merge_btn.setCheckable(True)
        self.crop_btn.setCheckable(True)  # 设置为可选中状态
        self.settings_btn.setChecked(True)
        
        # 连接按钮信号
        self.settings_btn.clicked.connect(lambda: self.switch_page(0))
        self.process_btn.clicked.connect(self.on_process_btn_clicked)
        self.merge_btn.clicked.connect(self.on_merge_btn_clicked)
        self.crop_btn.clicked.connect(self.on_crop_btn_clicked)  # 连接裁切按钮信号
        
        # 添加按钮到左侧布局
        left_layout.addWidget(self.settings_btn)
        left_layout.addWidget(self.process_btn)
        left_layout.addWidget(self.merge_btn)
        left_layout.addWidget(self.crop_btn)  # 添加裁切按钮到布局
        left_layout.addStretch()
        
        return left_panel
    
    def switch_page(self, index):
        """切换页面"""
        self.content_stack.setCurrentIndex(index)
        
        # 更新按钮状态
        self.settings_btn.setChecked(index == 0)
        self.process_btn.setChecked(index == 1)
        self.merge_btn.setChecked(index == 2)
        self.crop_btn.setChecked(index == 3)  # 更新裁切按钮状态
    
    def on_process_btn_clicked(self):
        """处理视频处理按钮点击事件"""
        if not self.process_btn.isEnabled():
            QMessageBox.information(self, "提示", "请先完成初始设置")
            return
        self.switch_page(1)
    
    def on_merge_btn_clicked(self):
        """处理左右眼合并按钮点击事件"""
        self.log_text.clear()
        self.append_log("===== 开始合并左右眼视频 =====")
        if not self.merge_btn.isEnabled():
            QMessageBox.information(self, "提示", "请先完成初始设置")
            return
        self.switch_page(2)
    
    def on_crop_btn_clicked(self):
        """处理视频裁切按钮点击事件"""
        self.log_text.clear()
        self.append_log("===== 开始视频裁切 =====")
        if not self.crop_btn.isEnabled():
            QMessageBox.information(self, "提示", "请先完成初始设置")
            return
        self.switch_page(3)
    
    def center_window(self):
        """将窗口居中显示"""
        frame_geometry = self.frameGeometry()
        screen_center = QDesktopWidget().availableGeometry().center()
        frame_geometry.moveCenter(screen_center)
        self.move(frame_geometry.topLeft())
    
    def create_icon_from_data(self):
        """从base64编码的SVG数据创建图标"""
        try:
            icon_data_base64 = icon_data.get_3d_data()
            svg_data = base64.b64decode(icon_data_base64)
            pixmap = QPixmap()
            pixmap.loadFromData(svg_data)
            return QIcon(pixmap)
        except Exception as e:
            print(f"创建图标失败: {e}")
            return QIcon()
    
    def update_hardware_options(self, hardware_info):
        """更新硬件加速选项"""
        # 清空下拉列表
        self.ffmpeg_accel_combo.clear()
        self.midas_accel_combo.clear()
        self.stereo_accel_combo.clear()
        
        # 添加CPU选项（始终可用）
        self.ffmpeg_accel_combo.addItem("cpu")
        self.midas_accel_combo.addItem("cpu")
        self.stereo_accel_combo.addItem("cpu (CPU处理)")
        
        # 添加CUDA选项（如果可用）
        if hardware_info.get("cuda", False):
            self.ffmpeg_accel_combo.addItem("cuda")
            self.midas_accel_combo.addItem("cuda")
            self.stereo_accel_combo.addItem("cuda (NVIDIA GPU加速)")
            self.append_log(f"检测到CUDA支持: {hardware_info.get('cuda_info', '')}")
        
        # 添加其他硬件加速选项
        if hardware_info.get("dxva2", False):
            self.ffmpeg_accel_combo.addItem("dxva2")
        
        if hardware_info.get("qsv", False):
            self.ffmpeg_accel_combo.addItem("qsv")
        
        if hardware_info.get("d3d11va", False):
            self.ffmpeg_accel_combo.addItem("d3d11va")
        
        if hardware_info.get("opencl", False):
            self.midas_accel_combo.addItem("opencl")
            self.stereo_accel_combo.addItem("opencl (OpenCL加速)")
        
        if hardware_info.get("vulkan", False):
            self.ffmpeg_accel_combo.addItem("vulkan")
        
        # 默认选择CPU
        self.ffmpeg_accel_combo.setCurrentText("cpu")
        self.midas_accel_combo.setCurrentText("cpu")
        self.stereo_accel_combo.setCurrentIndex(0)  # cpu
        
        # 保存当前选择
        self.ffmpeg_accel = "cpu"
        self.midas_accel = "cpu"
        self.stereo_accel = "cpu"
        
        # 先断开旧的连接（如果存在）
        try:
            self.ffmpeg_accel_combo.currentTextChanged.disconnect()
            self.midas_accel_combo.currentTextChanged.disconnect()
            self.stereo_accel_combo.currentTextChanged.disconnect()
        except:
            pass  # 如果没有连接，忽略错误
        
        # 连接信号
        self.ffmpeg_accel_combo.currentTextChanged.connect(self.update_ffmpeg_accel)
        self.midas_accel_combo.currentTextChanged.connect(self.update_midas_accel)
        self.stereo_accel_combo.currentTextChanged.connect(self.update_stereo_accel)
    
    def append_log(self, message):
        """添加日志"""
        self.log_text.append(message)
        # 只有在自动滚动选项开启或未定义时才滚动到底部
        if not hasattr(self, 'auto_scroll_check') or self.auto_scroll_check.isChecked():
            self.log_text.verticalScrollBar().setValue(self.log_text.verticalScrollBar().maximum())
    
    def update_ffmpeg_accel(self, accel_type):
        """更新FFmpeg硬件加速选项"""
        self.ffmpeg_accel = accel_type
        self.append_log(f"FFmpeg硬件加速设置为: {accel_type}")
    
    def update_midas_accel(self, accel_type):
        """更新MiDaS硬件加速选项"""
        self.midas_accel = accel_type
        self.append_log(f"MiDaS硬件加速设置为: {accel_type}")
    
    def update_stereo_accel(self, accel_type):
        """更新立体视图生成硬件加速选项"""
        # 从选项文本中提取加速类型（去掉描述部分）
        accel = accel_type.split(" ")[0]
        self.stereo_accel = accel
        self.append_log(f"立体视图生成硬件加速设置为: {accel}")
    
    def showEvent(self, event):
        """窗口显示事件"""
        super().showEvent(event)
        
        # 确保样式在窗口显示时应用
        self.apply_content_styles()

    def apply_content_styles(self):
        """应用内容区域样式，模拟毛玻璃效果"""
        from style import style_content_area, style_content_controls
        from PyQt5.QtWidgets import QGroupBox
        
        # 设置内容区域整体样式
        style_content_area(self.content_stack)
        
        # 为每个页面应用样式
        for i in range(self.content_stack.count()):
            page_widget = self.content_stack.widget(i)
            style_content_controls(page_widget)
            
            # 为每个GroupBox应用半透明背景
            for group_box in page_widget.findChildren(QGroupBox):
                self.apply_translucent_background(group_box)

    def apply_translucent_background(self, widget):
        """应用半透明背景到控件"""
        from style import set_widget_palette
        from PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit, QComboBox, QSpinBox
        
        set_widget_palette(widget)
        
        # 递归应用到子控件
        for child in widget.children():
            if isinstance(child, QWidget) and not (isinstance(child, QPushButton) or 
                                                isinstance(child, QLineEdit) or
                                                isinstance(child, QComboBox) or
                                                isinstance(child, QSpinBox)):
                self.apply_translucent_background(child)